package com.recource.util;

import com.recource.domain.FileAssets;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;


/**
 * @author yujie
 * @createTime 2023/1/5 10:21
 * @description
 */
@Slf4j
public class SystemUtil {
    public static FileAssets process(MultipartFile multipartFile, String root) {
        try{
            String key = UUID.randomUUID().toString();
            String fileDir = root + StringPool.SLASH;
            File dir = new File(fileDir);
            dir.mkdirs();
            String filePath = fileDir + key;
            File file = new File(filePath);
            if(!file.exists()){
                file.createNewFile();
            }
            FileOutputStream os = new FileOutputStream(filePath);
            multipartFile.getInputStream().transferTo(os);
            FileAssets fileAssets = new FileAssets();
            fileAssets.setName(multipartFile.getOriginalFilename());
            fileAssets.setFileKey(key);
            fileAssets.setFlod(root);
            fileAssets.setFileType(multipartFile.getContentType());
            return fileAssets;
        }catch (Exception e){
            log.error("上传文件失败:{}", e.getClass().getSimpleName(), e);
            throw  new RuntimeException("文件上传失败");
        }
    }

    public static FileInputStream getFile(String flod, String key) {
        try {
            return new FileInputStream(new File(flod, key));
        } catch (Exception e) {
            log.error(e.getClass().getSimpleName(), e);
            throw new RuntimeException("文件不存在");
        }
    }

}
